package com.zoe.onelink.sentinel.autoconfigure;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.sentinel.SentinelProperties;
import com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration;
import com.alibaba.cloud.sentinel.custom.SentinelDataSourceHandler;
import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.zoe.onelink.sentinel.handler.OnelinkNacosSentinelDataSourceHandler;
import com.zoe.onelink.sentinel.handler.OnelinkUrlBlockHandler;
import com.zoe.onelink.sentinel.property.OnelinkSentinelProperties;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.servlet.Filter;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-04-18
 */
@Configuration
@EnableConfigurationProperties(OnelinkSentinelProperties.class)
@AutoConfigureBefore(SentinelAutoConfiguration.class)
public class OnelinkSentinelAutoConfiguration {

    @Bean
    @ConditionalOnClass(NacosConfigProperties.class)
    @ConditionalOnProperty(prefix = OnelinkSentinelProperties.PREFIX, value = "datasource-type", havingValue = "nacos", matchIfMissing = true)
    public SentinelDataSourceHandler onelinkNacosSentinelDataSourceHandler(DefaultListableBeanFactory beanFactory,
                                                                           SentinelProperties sentinelProperties,
                                                                           Environment env) {
        return new OnelinkNacosSentinelDataSourceHandler(beanFactory, sentinelProperties, env);
    }

    @Bean
    public FilterRegistrationBean<Filter> sentinelFilterRegistration() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CommonFilter());
        registration.addUrlPatterns("/*");
        registration.setName("sentinelFilter");
        registration.setOrder(1);
        return registration;
    }

    @Bean
    @ConditionalOnMissingBean
    public UrlBlockHandler onelinkUrlBlockHandler() {
        return new OnelinkUrlBlockHandler();
    }

}
